package middlewares

import (
	"gitee.com/lv_baobao/gcore/helper"
	"github.com/gin-gonic/gin"
	"net/http"
)

func TokenMiddleware(validateToken bool) gin.HandlerFunc {
	return func(c *gin.Context) {
		if !validateToken {
			c.Next()
			return
		}
		var token = c.Request.Header.Get("token")
		if token == "" {
			var cook, _ = c.Request.Cookie("token")
			if cook != nil {
				token = cook.Value
			}
		}
		if token == "" {
			//c.AbortWithStatus(http.StatusNoContent)
			helper.GetHttpResponseInstance().SessionInValid(c)
			//c.AbortWithStatus(http.StatusBadRequest)
			c.AbortWithStatus(http.StatusOK)
			return
		}
		if token == "BaseServiceadmin" {
			c.Next()
			return
		}
		tokenInfo := NewUserTokenCache().GetTokenInfo(token)
		if tokenInfo == nil || tokenInfo.UserID == 0 {
			helper.GetHttpResponseInstance().SessionInValid(c)
			c.AbortWithStatus(http.StatusOK)
			return
		}
		NewUserTokenCache().Refresh(token)
		c.Next()
	}
}
